package com.ybkj.daijia.server.event.listener;

import com.ybkj.daijia.PushData;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiMember;
import com.ybkj.daijia.server.event.model.OrderCancelYupaiEvent;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class OrderCancelYupaiEventListener implements ApplicationListener<OrderCancelYupaiEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(OrderCancelYupaiEventListener.class);

    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DriverService driverService;

    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private MemberService memberService;


    @Override
    @Async
    public void onApplicationEvent(OrderCancelYupaiEvent event) {

        logger.debug("order cancelyupaidan event:{}", "");

        Order order = (Order) event.getSource();
        Driver driver = event.getDriver();
        Integer oldDriverStatus = event.getLastDriverStatus();

        if (null != driver) {
            //发送短信
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            if (settingUtils.get().isSmsMainCompany()) {
                driverCompany = companyService.getMain();
            }
            SmsTemplet templet = smsService.findByAlias(driverCompany.getId(), SmsType.cancelOrder);
            if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                try {
                    //smsService.sendSms(driver.getPhone(), "cancelOrder", "{\"订单号\":\""+"***"+order.getOrderNumber().substring(8)+"\"}", driverCompany.getId(), 0, driverCompany.getSignName());
                    //短信发送（改）
                    com.alibaba.fastjson.JSONObject smsParam = new com.alibaba.fastjson.JSONObject();
                    smsParam.put("order", order.getOrderNumber().substring(8));
                    smsService.sendSms(driver.getPhone(), templet.getTemplateId(),
                        smsParam.toJSONString(), driverCompany.getId(), 0,
                        driverCompany.getSignName());
                } catch (Exception e) {
                    logger.error("发送短信发生异常：{}", e.getMessage());
                }
            }
        }

        if (null == oldDriverStatus || oldDriverStatus != Driver.DRIVER_OFFLINE) {
            //web推送
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("driverID", driver.getId());
            jsonObject.put("type", "cancelyupaidan");
            Company mainCompany = companyService.getMain();
            WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());
        //给客户推送
        passenger.setCid(memberService.findCid(passenger.getId()));
        if (StringUtils.isNotBlank(passenger.getCid())) {
            try {
                //发送设备推送
                PushData pushData = new PushData();
                pushData.setType("CANCEL_ORDER");
                pushData.setTitle("订单被销单");
                pushData.setDescription("您的工单被销单了,单号:" + order.getOrderNumber());
                pushData.setData(order.getId());

                GeTuiMember.push(passenger, pushData, settingUtils.get());
            } catch (IOException e) {
                logger.debug("push error : " + e.getMessage());
            }
        }


    }

}
